package nslookup;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class DnsLookup
{
	static String failure = "Could not find: ";
	public DnsLookup()
	{
		//nothing really to do here
	}
	
	public String lookup (String s)
	{
		try
		{
			InetAddress ia = InetAddress.getByName(s);
			String returnVal;
			
			if(this.printHostname(s))
			{
				returnVal = ia.getHostName();
			}
			else
			{
				returnVal = ia.getHostAddress();
			}
			
			returnVal = returnVal.concat(" : class ");
			returnVal = returnVal.concat(this.getAddressClass(ia.getHostAddress()));
			return returnVal;
			
		} catch (UnknownHostException e)
		{
			return DnsLookup.failure.concat(s);
		}
	}
	
	public String getAddressClass (String s)
	{
		String returnVal;
		String [] tokens = s.split("[.]");
		int firstByte = Integer.parseInt(tokens[0]);
		
		if(firstByte > 0 && firstByte < 128)
			returnVal = "A";
		else if(firstByte > 127 && firstByte < 192)
			returnVal = "B";
		else if(firstByte > 191 && firstByte < 224)
			returnVal = "C";
		else
			returnVal = "D";
		
		return returnVal;
	}
	
	public boolean printHostname (String s)
	{
		String [] tokens = s.split("[.]");
		
		if(tokens.length == 4)
		{
			try
			{
				boolean ok = true;
				for(int i = 0; i < tokens.length && ok == true; i++)
				{
					int current = Integer.parseInt(tokens[i]);
					ok = (current < 256 && current > -1);
				}
				return ok;
			}
			catch (NumberFormatException e)
			{
				//one of the tokens was not a valid int
				return false;
			}
		}
		else
		{
			//if the length is not 4 can't be a valid ipv4 address
			return false;
		}
	}
}
